package router

import (
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/service"
	"iris-wms/common/tools"
	"iris-wms/common/tools/result"

	"github.com/kataras/iris/v12"
)

func NewAdminMenuRoute() *adminMenuRoute {
	return &adminMenuRoute{}
}

type adminMenuRoute struct{}

func (r *adminMenuRoute) Create(ctx iris.Context, service_ service.AdminMenuService) {
	var in din.AdminMenuIn
	if err := ctx.ReadJSON(&in); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	if err := service_.Create(in); err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *adminMenuRoute) Delete(ctx iris.Context, service_ service.AdminMenuService) {
	var idList = make([]uint, 0)
	if err := ctx.ReadJSON(&idList); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	if err := service_.DeleteByIdList(idList); err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *adminMenuRoute) Edit(ctx iris.Context, service_ service.AdminMenuService) {
	var in din.AdminMenuIn
	if err := ctx.ReadJSON(&in); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}

	if err := service_.Update(in); err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *adminMenuRoute) List(ctx iris.Context, service_ service.AdminMenuService) {
	rows, err := service_.GetList(uint(ctx.URLParamUint64("rid")))
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OKData(ctx, rows)
}

func (r *adminMenuRoute) OwnList(ctx iris.Context, service_ service.AdminMenuService) {
	rows, err := service_.GetOwnList(tools.GetUserID(ctx))
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	buttonService := service.NewAdminButtonService()
	buttonList, err := buttonService.GetList()
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OKData(ctx, iris.Map{
		"menuList":   rows,
		"buttonList": buttonList,
	})
}
